import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:hkzf_flutter/config.dart';
import 'package:hkzf_flutter/dio/room_detail_data.dart';
import 'package:hkzf_flutter/pages/room_detail/data.dart';
import 'package:hkzf_flutter/utils/dio_http.dart';
import 'package:hkzf_flutter/utils/expandable_text.dart';
import 'package:hkzf_flutter/widgets/common_swiper.dart';
import 'package:hkzf_flutter/widgets/common_tag.dart';
import 'package:hkzf_flutter/widgets/common_title.dart';
import 'package:hkzf_flutter/widgets/information/index.dart';
import 'package:hkzf_flutter/widgets/room_appliance_item.dart';
import 'package:share_plus/share_plus.dart';

const bottomBtnStyel = TextStyle(
  fontSize: 20.0,
  color: Colors.white,
);

// 房屋详情页
class RoomDetailPage extends StatefulWidget {
  // 房屋id
  final String roomId;
  const RoomDetailPage({super.key, required this.roomId});

  @override
  State<RoomDetailPage> createState() => _RoomDetailPageState();
}

class _RoomDetailPageState extends State<RoomDetailPage> {
  // 房屋数据项
  RoomDetailData data = defaultData;
  // 是否收藏
  bool isLike = false;
  // 展示所有房源副标题描述
  bool showAllText = false;
  // 获取房源详细数据
  _getData() async{
    var path = '/houses/${widget.roomId}';
    var res = await DioHttp.of(context).get(path);
    var rewMap = json.decode(res.toString());
    var resData = rewMap['body'];
    var roomDeTailData = RoomDetailData.fromJson(resData);
    // 处理房屋图片列表
    roomDeTailData.houseImgs = roomDeTailData.houseImgs!.map((item) => Config.BaseUrl + item).toList();
    setState(() {
       data = roomDeTailData;
    });
  }


  @override
  void initState() {
    // 确保在 UI 完成构建后再进行某些操作（如数据加载）
    WidgetsBinding.instance.addPostFrameCallback((_){
       _getData();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    if(data == null) return Container();
    return Scaffold(
      appBar: AppBar(
        title: Text(data!.title!),
        backgroundColor:Colors.green,
        actions: [
          IconButton(
            onPressed: (){
              // Share.share('https://www.bilibili.com/');
              SharePlus.instance.share(
                  ShareParams(
                   text: '快来查看这个房源：https://www.bilibili.com/',
                   subject: '房屋详情分享',
                 ),
                );
            }, 
            icon: const Icon(Icons.share)
          )
        ],
      ),
      body: Stack(
        children: [
          // 如果某个子组件没有指定 top、bottom、left、right 等定位参数，它会尽可能地填满整个 Stack 的空间
          // Flutter 布局引擎会自动为 ListView 分配剩余的高度：屏幕可用高度 -底部定位栏高度
          ListView(
            children: [
              CommonSwiper(
                imgList: data?.houseImgs
              ),
              CommonTitle(title:data?.title),
              Container(
                padding: const EdgeInsets.only(left: 10.0),
                child: Row(
                  children: [
                    Text(data!.price.toString(),style: const TextStyle(
                      fontSize: 20.0,
                      color: Colors.pink
                    ),),
                    const Text(
                      '元/月(押一付三)',
                      style: TextStyle(
                        fontSize: 14.0,
                        color: Colors.pink
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                padding: const EdgeInsets.only(left: 10.0,top: 6.0,bottom: 6.0),
                child: Wrap(
                  spacing: 4.0,
                  children: data!.tags!.map((pre)=>CommonTag.fromTitle(
                    pre
                  )).toList(),
                ),
              ),
              const Divider(
                color: Colors.grey,// 设置分割线的颜色
                indent: 10.0,// 设置分割线左侧的缩进（留白）
                endIndent: 10.0,// 设置分割线右侧的缩进（留白）
              ),
              Container(
                padding: const EdgeInsets.all(10.0),
                child: Wrap(
                  spacing: 10.0,
                  runSpacing: 20.0,
                  children: [
                   BaseInfoItem('面积: ${data?.size}平米'),
                   BaseInfoItem('楼层: ${data?.size}'),
                   BaseInfoItem('房型: ${data?.roomType}'),
                   const BaseInfoItem('装修：精装')
                  ],
                ),
              ),
              const CommonTitle(title: '房屋配置',),
              RoomApplianceList(
                list: data!.applicances,
              ),
              const CommonTitle(title: '房屋概况',),
              Container(
                padding: const EdgeInsets.only(left: 10.0,right: 10.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // (showAllText? '收起' : '展开'
                    // Text(
                    //   data!.subTitle ?? '暂无房屋概况',
                    //   maxLines: showAllText ? null : 5,
                    //   overflow: showAllText ? TextOverflow.visible:TextOverflow.ellipsis,
                    // ),
                    ExpandableText(
                     text: data!.subTitle ?? '暂无房屋概况',
                     showLines: 3,// 默认显示行数
                     isExpand:showAllText,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        InkWell(
                          onTap: () {
                            setState(() {
                              showAllText = !showAllText;
                            });
                          },
                          child: Row(
                            children: [
                              Text(showAllText? '收起' : '展开'),
                              Icon(showAllText? Icons.keyboard_arrow_up:Icons.keyboard_arrow_down)
                            ],
                          ),
                        ),
                        const Text('举报'),
                      ],
                    )
                  ],
                ),
              ),
              const CommonTitle(title: '猜你喜欢',),
              InformationPanel(showTitle: false),
            ],
          ),
          Positioned(
            width: MediaQuery.of(context).size.width,
            height: 100.0,
            bottom: 0,
            child: Container(
              color:Colors.grey[200],
              padding: const EdgeInsets.only(top: 10.0,right: 20.0,left: 20.0,bottom: 20.0),
              child: Row(
                children: [
                  GestureDetector(
                    behavior: HitTestBehavior.translucent,// 事件穿透
                    onTap: (){
                      setState(() {
                        isLike = !isLike;
                      });
                    },
                    child: Container(
                      margin: const EdgeInsets.only(right: 10.0),
                      height: 50.0,
                      width: 40.0,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Icon(
                            isLike ? Icons.star:Icons.star_border,
                            size: 24.0,
                            color: isLike?Colors.orange:Colors.black,
                          ),
                          Text(
                            isLike?'已收藏':'收藏',
                            style: const TextStyle(
                              fontSize: 12.0
                            )
                          ,)
                        ],
                      ),
                    ),
                  ),
                  Expanded(
                    child: GestureDetector(
                      onTap: () {
                        
                      },
                      child: Container(
                         height: 50.0,
                         margin: const EdgeInsets.only(right: 5.0),
                         decoration: BoxDecoration(
                            color: Colors.cyan,
                            borderRadius: BorderRadius.circular(10.0)
                         ),
                         padding: const EdgeInsets.all(10.0),
                         child: const Center(
                          child: Text('联系房东',style: bottomBtnStyel,),
                         ),
                      ),
                    )
                  ),
                  Expanded(
                    child: GestureDetector(
                      onTap: () {
                        
                      },
                      child: Container(
                         height: 50.0,
                         decoration: BoxDecoration(
                            color: Colors.green,
                            borderRadius: BorderRadius.circular(10.0)
                         ),
                         padding: const EdgeInsets.all(10.0),
                         child: const Center(
                          child: Text('预约看房',style: bottomBtnStyel,),
                         ),
                      ),
                    )
                  )
                ],
              ),
            ),)
        ],
      ),
    );
  }
}


class BaseInfoItem extends StatelessWidget {
  final String? content;
  const BaseInfoItem(this.content,{super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
       width: (MediaQuery.of(context).size.width - 10* 3) / 2,
       child: Text(content!,style: const TextStyle(
          fontSize: 16.0
       ),),
    );
  }
}